﻿using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;
using System.Windows.Forms;
using System.ServiceProcess;
using OfficeMiddlewareCore;
using System.Collections;
using System.Configuration.Install;
using System.IO;
using System.Threading;
using System.Net;

namespace OfficeMiddleware
{
    internal static class Program
    {
        private static Mutex _mutex;


        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        // [System.Diagnostics.DebuggerStepThrough]
        static void Main()
        {
            _mutex = new Mutex(true, "正文运行环境", out bool createdNew);
            if (!createdNew)
            {
                Environment.Exit(0);
                return;
            }
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErros) => true;

#if !DEBUG
            var identity = WindowsIdentity.GetCurrent();
            var principal = new WindowsPrincipal(identity);
            if (!principal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                var startInfo = new ProcessStartInfo
                {
                    UseShellExecute = true,
                    WorkingDirectory = Environment.CurrentDirectory,
                    FileName = Application.ExecutablePath,
                    Verb = "runas"
                };
                try
                {
                    Process.Start(startInfo);
                }
                catch
                {
                }
                finally
                {
                    Application.Exit();
                }
                return;
            }

            var serviceName = "正文运行环境守护进程";
            var servicePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "OfficeMiddlewareService.exe");
            var services = ServiceController.GetServices();
            if (ServiceController.GetServices().All(a => a.ServiceName != serviceName))
            {
                try
                {
                    using (AssemblyInstaller installer = new AssemblyInstaller())
                    {
                        installer.UseNewContext = true;
                        installer.Path = servicePath;
                        IDictionary savedState = new Hashtable();
                        installer.Install(savedState);
                        installer.Commit(savedState);
                        LogHelper.Info("启动守护服务成功");
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error("启动守护服务失败" + ex.Message, ex);
                }
            }
            try
            {
                using (var sc = new ServiceController(serviceName))
                {
                    if (sc.Status == ServiceControllerStatus.Stopped)
                    {
                        sc.Start();
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("启动守护服务失败" + ex.Message, ex);

            }
#endif
            //var hasOffice = Type.GetTypeFromProgID("Word.Application") != null;
            //RegistryKey wpsLibrary = Registry.CurrentUser.OpenSubKey(@"Software\Kingsoft\Office\6.0\common");
            //var hasWps = wpsLibrary != null && wpsLibrary.GetValue("InstallRoot") != null;

            //if (hasOffice && hasWps)
            //{
            //    MessageBox.Show("检测到您的计算机有2种文档处理软件，请与管理员联系。");
            //}
            //else if (!hasOffice && !hasWps)
            //{
            //    MessageBox.Show("未检测到可用的文档处理软件，建议安装，如有疑问请与管理员联系");
            //}

            Application.Run(new MainForm());

        }

    }


}
